﻿using System;
using System.Collections.Generic;
using System.Text;
using M=XinYiOffice.Model;
using B=XinYiOffice.BLL;
using XinYiOffice.Common;
using System.Web;
using XinYiOffice.Config;
using XinYiOffice.Basic;
using System.Data;

namespace XinYiOffice.Web.UI
{
    public class BasicPage : System.Web.UI.Page
    {
        #region //属性成员
        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        public M.Accounts CurrentAccount
        {
            get
            {
                if (_CurrentAccount == null)
                {
                    int uid = GetCliCookie();
                    if (uid != 0)
                    {
                        _CurrentAccount = new B.Accounts().GetModel(uid);
                    }
                }

                return _CurrentAccount;
            }

        }
        
        /// <summary>
        /// 当前登录的租户信息
        /// </summary>
        public M.LocalTenants CurrentTenant
        {
            get 
            {
                if (_CurrentTenant == null)
                {
                    int tid = GetCliCookieTenant(); ;
                    if(tid!=0)
                    {
                        _CurrentTenant=new B.LocalTenants().GetModel(tid);
                    }
                }

                return _CurrentTenant;
            }
        }

        public DataTable CurrentRolePermissions
        {
            get 
            {
                if (_CurrentRolePermissions == null || _CurrentRolePermissions.Rows.Count<=0)
                {
                    string mysql = string.Format("select  PermissionId,AccountId,Sign,Name,TenantId from vAccountRolesPermissions where TenantId={0} ",CurrentTenantId);

                    DataSet ds = Common.DbHelperSQL.Query(mysql);
                    
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        _CurrentRolePermissions = ds.Tables[0];
                    }

                }

                return _CurrentRolePermissions;
            }
        }
        
        public string CurrentTenantNameCn
        {
            get
            {
                if (CurrentTenant != null)
                {
                    return CurrentTenant.NameCn;
                }

                return string.Empty;
            }
        }

        public string CurrentAccountNiceName
        {
            get
            {
                if (CurrentAccount != null)
                {
                    return CurrentAccount.NiceName;
                }

                return string.Empty;
            }
        }
        public string CurrentAccountTrueName
        {
            get
            {
                if (CurrentAccount != null)
                {
                    return CurrentAccount.FullName;
                }

                return string.Empty;
            }
        }

        private int _CurrentAccountId;
        public int CurrentAccountId
        {
            get
            {
                if (_CurrentAccountId== 0)
                {
                    _CurrentAccountId = SafeConvert.ToInt(GetCliCookie());
                }
                return _CurrentAccountId;
            }
        }
        
        private int _CurrentTenantId;
        public int CurrentTenantId
        {
            get
            {
                if (_CurrentTenantId==0)
                {
                    _CurrentTenantId = GetCliCookieTenant();
                   
                }
                return _CurrentTenantId;
            }
        }

        private M.Accounts _CurrentAccount;
        private M.LocalTenants _CurrentTenant;
        private DataTable _CurrentRolePermissions;
        
        #endregion

        #region //方法
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Load += new System.EventHandler(PageBase_Load);
            this.Error += new System.EventHandler(PageBase_Error);
        }

        protected void PageBase_Error(object sender, System.EventArgs e)
        {
            Exception currentError = HttpContext.Current.Server.GetLastError();
            EasyLog.WriteLog(currentError);
            SystemJournalServer.SetErrorLog(currentError,CurrentAccountId,CurrentTenantId);

            //OutLoginAction.OutAndClearAll();

            //string LoginUrl = "/OutLogin.aspx";

            //Response.Redirect("/Error.aspx");
            //Response.Clear();
            //Response.Redirect(LoginUrl);
            //string WriteJs = @"<script>if(top==self){window.location.href='" + LoginUrl + "'}else{window.top.location.href='" + LoginUrl + "'}</script>";
            //Response.Write(WriteJs);
            //xytools.write(WriteJs);
        }

        private void PageBase_Load(object sender, EventArgs e)
        {
            ValidateUser(this);
        }

        /// <summary>
        /// 验证是否登录
        /// </summary>
        /// <param name="mypage">当前页面类</param>
        public void ValidateUser(System.Web.UI.Page mypage)
        {
            if (!mypage.Page.IsPostBack)
            {
                if (GetCliCookie() == 0)
                {
                    string LoginUrl = xytools.ApplicationPath() + "/Login.aspx";

                    string WriteJs = @"<script>if(top==self){alert('未登录或操作超时,请登录!');window.location.href='" + LoginUrl + "'}else{alert('未登录或操作超时,请登录!');window.top.location.href='" + LoginUrl + "'}</script>";

                    xytools.write(WriteJs);
                }
            }

        }

        public int GetCliCookie()
        {
            int i = 0;

            string str=SafeConvert.ToString(CookieHelper.GetCookie("xyo_cookie_aid"));
            if(!string.IsNullOrEmpty(str))
            {
                i = SafeConvert.ToInt(DESEncrypt.Decrypt(str));
            }
            
            return i;
        }

        /// <summary>
        /// 获取当前cookie的 租户ID
        /// </summary>
        /// <returns></returns>
        public int GetCliCookieTenant()
        {
            int i = 0;

            string str = SafeConvert.ToString(CookieHelper.GetCookie("xyo_cookie_tenantid"));
            if (!string.IsNullOrEmpty(str))
            {
                i = SafeConvert.ToInt(DESEncrypt.Decrypt(str));
            }

            return i;
        }

        /// <summary>
        /// 根据签名判断权限(一般指页面访问权限)
        /// </summary>
        /// <param name="permissionSign"></param>
        /// <returns></returns>
        public bool ValidatePermission(string permissionSign)
        {
            permissionSign = xytools.Trim(permissionSign);

            ///return PermissionService.IsValid(CurrentAccount, permissionSign);
            return PermissionService.IsValid(CurrentRolePermissions,CurrentAccountId, permissionSign);
        }

        public void NoPermissionPage()
        {
            xytools.href_url("/NoPermission.aspx");
        }

        #endregion

    }
}
